package com.zyw.datasource.annotation;

import com.zyw.datasource.DataSourceContextHolder;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

import java.lang.reflect.Method;

/**
 * datasource 注解 切面工具
 *
 * @author zhangyw
 * @date 16/12/16 15:55
 */
//@Component
//@Aspect
public class DataSourceAspect implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        final DataSource dataSource = method.getAnnotation(DataSource.class);
        DataSourceContextHolder.setDataSourceKey(dataSource.value());
    }

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        DataSourceContextHolder.clear();
    }

    /**
     * 抛出异常后 清空多数据源缓存
     *
     * @param ex 异常信息
     */
    public void afterThrowing(Exception ex) {
        DataSourceContextHolder.clear();
    }
}
